import { Image, List,InfiniteScroll } from 'antd-mobile'
// mock数据
import {getCommentList,ListRes} from '@/apis/channels'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
type Props = {
  channelId: string
}
const HomeList = (props:Props) => {
  const { channelId } = props
  const [listRes,setListRes] = useState<ListRes>({
    results: [],
    pre_timestamp: '2023-11-17 13:15:32',
  })
  useEffect(() => {
    const getList = async() => {
      const res = await getCommentList({
        channel_id: channelId,
        timestamp: '2023-11-17 13:15:32',
      })
      setListRes(res.data.data)
      // console.log(listRes)
    }
    getList()
  },[channelId])

  // 实现无限加载
  const [hasMore,setHasMore] = useState(true)
  const loadMore = async () => {
      const res = await getCommentList({
        channel_id: channelId,
        timestamp: listRes.pre_timestamp,
      })
      // 没有数据立刻停止
      if (res.data.data.results.length === 0) {
        setHasMore(false)
      }
      setListRes({
        // 拼接新老列表数据
        results: [...listRes.results, ...res.data.data.results],
        // 重置时间参数 为下一次请求做准备
        pre_timestamp: res.data.data.pre_timestamp,
      })
  }

  // 页面跳转
  const navigate = useNavigate()
  const goDetail = (id:string) => {
    navigate(`/detail?id=${id}`)
  }
  return (
    <>
      <List>
        {listRes.results.map((item) => (
          <List.Item
            key={item.art_id}
            onClick={() => goDetail(item.art_id)}
            prefix={
              <Image
                src={item.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
            >
            {item.title}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
    </>
  )
}

export default HomeList